__author__ = 'vincent LIU'

import csv
import xlrd
import TradingDates
import os,time

def GetCls(fdate):
	clsdict = {}
	dpxdir = 'z:/data/WindDB/dpx/'
	fname=dpxdir+fdate+'.dpx.csv'
	reader=csv.reader(open(fname,'r'))
	next(reader)
	for line in reader:
		clsdict[line[0]]=float(line[6])
	return clsdict

class future_data():
	code = None
	amt = 0
	cur_px = 0
	pre_cls = 0
	cur_pnl = 0
	cur_mv = 0

class futureInfo():
	def __init__(self):
		self.cur_int = "0"#当前权益
		self.total_contract_value = "0"#合约总价值
		self.pre_close_right = "0"#前收盘权益
		self.avaliable_cash_deposit = "0"#可用保证金
		self.cur_pnl = "0"#当日盈亏
		self.cur_fare  = "0"#当日费用
		self.cur_in_cash = "0"#当日入金
		self.total_pnl = "0"#总盈亏
		self.f_table = []#期货数据表[合约代码，数量，求和项金额，占用保证金，现价，前结算价，当日盈亏，当日市值]

	def Clear(self):
		self.cur_int = "0"#当前权益
		self.total_contract_value = "0"#合约总价值
		self.pre_close_right = "0"#前收盘权益
		self.avaliable_cash_deposit = "0"#可用保证金
		self.cur_pnl = "0"#当日盈亏
		self.cur_fare  = "0"#当日费用
		self.cur_in_cash = "0"#当日入金
		self.total_pnl = "0"#总盈亏
		self.f_table.clear()

class fundInfo():
	def __init__(self):
		self.index = []
		self.name = ""
		self.value = ""

class nvValue:
	def  __init__(self,date,prod,nv_path):
		self.__prod = prod
		self.__nv_path = nv_path
		self.date = date
		self.__fname = self.__nv_path + self.date + ".prod"+prod+".xlsx"
		while not os.path.exists(self.__fname):
			print(self.__fname + " not existed")
			time.sleep(10)
			continue
		self.__wbrd = xlrd.open_workbook(self.__fname)
		'''
		function 1:use the field location
		note:load table about the production's foundation
		'''
		self.origin_asset = "0"#初始总资产
		self.origin_bond = "0"#初始保证金
		self.append_bond = "0"#追加保证金
		self.accumulate_interest = "0"#累计利息
		self.accumulate_buyback = "0"#累计回购
		self.financing = "0"#融资部分
		self.tcom = "0"#交易佣金
		self.total_pnl ="0"#总盈亏
		self.total_asset = "0"#总资产
		self.nvalue="0"#净资产
		self.Long ="0"#Long
		self.Short= "0"#Short
		self.net_exposure = "0"#净敞口
		self.longshort_balance = "0"#多空平衡
		self.orgin_bond2 = "0"#初始保证金
		self.lowest_bond = "0"#最低保证金
		self.cur_bond = "0"#现有保证金
		self.net_hold_bond_rate = "0"#净头寸维持保证金率
		self.longshort_bond_rate = "0"#多空平衡部分维持保证金率
		self.cur_nv="0"#当前净值
		self.lowest_bond_rate = "0"#最低保证金
		self.cur_bond_rate = "0"#现有保证
		'''
		function 2:use the relation of the filed and the value
		note:load table about the production's foundation
		'''
		self.fund_table = dict()
		########## table 2 ###########
		self.stk_acc_int = 0 #累计存入
		self.stk_cash =0#股票现金
		self.stk_today_mv = 0#当日股票市值
		self.stk_total_value = 0#市值总之
		self.stk_total_asset = 0#总资产
		self.stk_pnl = 0#除去停牌的
		self.holding_dict = {}#股票持仓量列表
		########## table 3 ###########
		self.f_info = futureInfo()#期货信息表
		self.f_t_table = []
		########## table 4 ###########
		'''
		trading details table
		order:tk,cls,num,mv,comm
		'''
		self.cur_trade_list = []
		self.all_trade_list = []
		self.stk_cur_comm = 0
		self.stk_all_comm = 0

	def Load_FundTable(self):
		'''
		function 2:use the relation of the field the value
		note:load table about the production's foundation
		'''
		table = self.__wbrd.sheet_by_name("每日账户情况")
		count = 0
		for j in range(0,table.ncols):
			for i in range(1,11):
				if not isinstance(table.cell(i,j).value,str):
					continue
				name = table.cell(i,j).value.strip("：")
				name = name.strip(":")
				if name == "":
					continue
				if name in self.fund_table:
					name+="2"
				if j == 3:
					self.fund_table[name] = [(i+1,j+2),table.cell(i,j+2).value,count]
				else:
					self.fund_table[name] = [(i+1,j+1),table.cell(i,j+1).value,count]
				count+=1
			j+=2
		return self.fund_table

	def Load_FutureInfo(self):
		'''
		function 2:use the relation of the field the value
		note:load table about the production's foundation
		'''
		table = self.__wbrd.sheet_by_name("每日账户情况")
		head_row = 14
		for j in range(0,table.ncols):
			if table.cell(head_row,j).value == "当前权益":
				self.f_info.cur_int = table.cell(head_row+1,j).value
			elif table.cell(head_row,j).value == "总合约价值":
				self.f_info.total_contract_value = table.cell(head_row+1,j).value
			elif table.cell(head_row,j).value == "前收盘权益":
				self.f_info.pre_close_right = table.cell(head_row+1,j).value
			elif table.cell(head_row,j).value == "可用保证金":
				self.f_info.avaliable_cash_deposit = table.cell(head_row+1,j).value
			elif table.cell(head_row,j).value == "当日盈亏":
				self.f_info.cur_pnl = table.cell(head_row+1,j).value
			elif table.cell(head_row,j).value == "当日交易费用":
				self.f_info.cur_fare = table.cell(head_row+1,j).value
			elif table.cell(head_row,j).value == "当日入金":
				self.f_info.cur_in_cash = table.cell(head_row+1,j).value
				if self.f_info.cur_in_cash == "":
					self.f_info.cur_in_cash = 0
			elif table.cell(head_row,j).value == "总盈亏:":
				self.f_info.total_pnl = table(head_row+1,j).value
		head_row = 17
		for j in range(0,table.ncols):
			if table.cell(head_row,j).value=="代码":
				for i in range(head_row+1,table.nrows):
					if table.cell(i,j).value in ["总计",""]:
						break
					code = table.cell(i,j).value
					if code == "(空白)":
						continue
					if table.cell(i,j+1).value != "":
						amt = int(table.cell(i,j+1).value)
					if table.cell(i,j+1).value != "":
						total_cash = float(table.cell(i,j+2).value)
					if table.cell(i,j+3).value != "":
						deposit = float(table.cell(i,j+3).value)
					if table.cell(i,j+4).value != "":
						px = float(table.cell(i,j+4).value)
					if table.cell(i,j+5).value != "":
						cls = float(table.cell(i,j+5).value)
					if table.cell(i,j+6).value != "":
						pnl = float(table.cell(i,j+6).value)
					if table.cell(i,j+7).value != "":
						mv = float(table.cell(i,j+7).value)
					if amt != 0:
						self.f_info.f_table.append([code,amt,total_cash,deposit,px,cls,pnl,mv])

	def GetFutureTable(self):
		return self.f_info.f_table

	def Load_StockInfo(self):
		'''
		function 2:use the relation of the field the value
		note:load table about the production's foundation
		'''
		table = self.__wbrd.sheet_by_name("每日账户情况")
		head_row = 14
		for j in range(0,table.ncols):
			if table.cell(head_row,j).value == "累计存入":
				self.stk_acc_int = float(table.cell(head_row+1,j).value)
			elif table.cell(head_row,j).value == "市值总值":
				self.stk_today_mv = float(table.cell(head_row+1,j).value)
			elif table.cell(head_row,j).value == "帐户总资产":
				self.stk_total_asset = float(table.cell(head_row+1,j).value)
			elif table.cell(head_row,j).value == "账户总分红":
				self.stk_total_dividen = float(table.cell(head_row+1,j).value)
			elif table.cell(head_row,j).value == "现金(含股息)":
				self.stk_cash = float(table.cell(head_row+1,j).value)
			elif table.cell(head_row,j).value == "金额总值":
				self.stk_total_trade_amount = float(table.cell(head_row+1,j).value)
			elif table.cell(head_row,j).value == "总盈亏 ":
				self.stk_pnl = float(table.cell(head_row+1,j).value)

	def Load_CurStockDetail(self):
		'''
		function 2:use the relation of the field the value
		note:load table about the production's foundation
		'''
		table = self.__wbrd.sheet_by_name("股票成交记录")
		for i in range(1,table.nrows):
			if table.cell(i,0).value != "":
				date = xlrd.xldate_as_tuple(table.cell(i,0).value,0)
				date = "{0}{1:02}{2:02}".format(date[0],date[1],date[2])
				tk = table.cell(i,2).value[0:6]
				tpx = table.cell(i,3).value
				shr = table.cell(i,4).value
				tcash = table.cell(i,5).value
				comm = table.cell(i,6).value
				if date == self.date:
					self.cur_trade_list.append([tk,tpx,shr,tcash,comm])
				else:
					self.all_trade_list.append([tk,tpx,shr,tcash,comm])
		for line in self.cur_trade_list:
			self.stk_cur_comm += line[4]
		for line in self.all_trade_list:
			self.stk_all_comm += line[4]

	def Load_FuutresTradeDetail(self):
		table = self.__wbrd.sheet_by_name("期货成交记录")
		for i in range(1,table.nrows):
			if table.cell(i,0).value =="":
				continue
			cdate = xlrd.xldate_as_tuple(table.cell(i,0).value,0)
			cdate = "{0}{1:02}{2:02}".format(cdate[0],cdate[1],cdate[2])
			if cdate == self.date:
				tk = table.cell(i,2).value[0:6]
				tpx = table.cell(i,3).value
				shr = table.cell(i,4).value
				self.f_t_table.append([tk,shr,tpx])
					#date = self.date[0:4] + "/" + self.date[4:6] + "/"
	def OutputFuturesTrade(self):
		fname = "P:\\NetValue\\production" + self.__prod +"\\portfolio\\actTrade\\futures_trade\\" + self.date + ".actTrade.futures.csv"
		print("[INFO] Output futurnes trade " + fname)
		fd = open(fname,'w')
		fd.write("#tk,shr,tpx\n")
		for line in self.f_t_table:
			fd.write("%s,%d,%.2f\n" % (line[0],-int(line[1]),float(line[2])))
		fd.close()
		print('[INFO] Success')

	def OutputFuturesHolding(self):
		ndate = TradingDates.GetNextDate(self.date)
		fname = "P:\\NetValue\\production"+ self.__prod +"\\portfolio\\actHolding\\futures_holding\\" + ndate + ".actHolding.futures.csv"
		print("[INFO] Output futurnes holding " + fname)
		fd = open(fname,'w')
		fd.write("#tk,shr,lastGoodCls\n")
		for line in self.f_info.f_table:
			fd.write("%s,%d,%.2f\n" % (line[0],-int(line[1]),float(line[4])))
		fd.close()
		print('[INFO] Success')


	def Clear_Value(self):
		self.date=""
		self.nvalue="0"#净资产
		self.tcom = "0"#交易佣金
		self.curfare="0"#当日交易费用
		self.cash ="0"#股票现金
		self.cur_int = "0"#当前权益
		self.cur_nv="0"#当前净值
		self.today_tk_mv = "0"#当日股票市值
		self.today_tk_mv_nostop = 0#除去停牌的
		self.holding_dict = {}#股票持仓量列表
		self.f_info.Clear()

	def WriteLine3(self,fd):
		fd.write("%s,%s\n" % (self.date,self.cur_nv))

	def WriteLine4(self,fd):
		fd.write("%s," % self.date)
		flist = sorted(self.fund_table.items(), key=lambda d:d[1][2], reverse = False )
		for tuple in flist:
			name = tuple[0]
			fd.write("%s," % self.fund_table[name][1])
		fd.write("\n")

	def WriteLine5(self,fd):
		ft = self.f_info
		#股指期货合约价值
		IFvalue = 0
		ICvalue = 0
		IHvalue = 0
		deposit = 0
		for f in ft.f_table:
			if f[1] >= 0 :
				if f[0][0:2]=="IF":
					IFvalue += f[7]
					deposit += f[3]
				elif f[0][0:2]=="IC":
					ICvalue += f[7]
					deposit += f[3]
				elif f[0][0:2] == "IH":
					IHvalue += f[7]
					deposit += f[3]
		fd.write("%s,%f,%f,%f,%f,%f,%s,%s,%s,%s,0,0\n" % (self.date,
		                                               deposit/float(self.fund_table["净资产"][1])*100,
		                                            float(self.stk_total_asset)/float(self.fund_table["净资产"][1])*100,
		                                            IFvalue,ICvalue,IHvalue,self.stk_today_mv,self.fund_table["净资产"][1],
		                                            self.fund_table["当前净值"][1],deposit))

	def WriteNetValueTable(self,fd,prod,stk_cur_pnl):
		"""

		:type self: object
		"""
		self.fundShare = float(self.fund_table["净资产"][1]) / float(self.fund_table["当前净值"][1])
		fd.write(u"production{0:s},{1:f},{2:f},{3:f},{4:f},{5:f},{6:f}, \
		{7:f},{8:f},{9:f},{10:f},{11:f},{12:f},\
		{13:f},{14:f},{15:f},{16:f},{17:f},{18:f},{19:f},{20:f}\n".format(prod,
		                                                           self.fund_table["净资产"][1],
		                                                           self.fund_table["当前净值"][1],
		                                                           self.fundShare,
		                                                           self.fund_table["Long"][1],
		                                                           self.fund_table["累计回购"][1],
		                                                           self.stk_total_dividen,
		                                                           self.stk_total_trade_amount,
		                                                           self.stk_all_comm,
		                                                           self.stk_acc_int,
		                                                           self.stk_cash,
		                                                           self.stk_total_asset,
		                                                           self.f_info.pre_close_right,
		                                                           self.f_info.cur_pnl,
		                                                           self.f_info.cur_fare,
		                                                           self.f_info.cur_in_cash,
		                                                           self.f_info.cur_int,
		                                                           self.f_info.total_contract_value,
		                                                           self.fund_table["总资产"][1],
		                                                           stk_cur_pnl,
		                                                           self.fund_table["Long"][1]
		                                                           ))
